﻿//https://leetcode.cn/problems/product-of-array-except-self/
class Solution {
public:
	vector<int> productExceptSelf(vector<int>& nums) {
		int len = nums.size();
		vector<int> dpLeft(len), dpRight(len);

		dpLeft[0] = 1;
		dpRight[len - 1] = 1;
		for (int i = 1; i < len; i++) {
			dpLeft[i] = nums[i - 1] * dpLeft[i - 1];
			dpRight[len - 1 - i] = nums[len - i] * dpRight[len - i];
		}

		vector<int> ret;
		for (int i = 0; i < len; i++) {
			ret.push_back(dpLeft[i] * dpRight[i]);
		}
		return ret;
	}
};

class Solution
{
public:
	vector<int> productExceptSelf(vector<int>& nums)
	{
		// lprod 表⽰：[0, i - 1] 区间内所有元素的乘积
// rprod 表⽰：[i + 1, n - 1] 区间内所有元素的乘积
		int n = nums.size();
		vector<int> lprod(n + 1), rprod(n + 1);
		lprod[0] = 1, rprod[n - 1] = 1;
		// 预处理前缀积以及后缀积
		for (int i = 1; i < n; i++)
			lprod[i] = lprod[i - 1] * nums[i - 1];
		for (int i = n - 2; i >= 0; i--)
			rprod[i] = rprod[i + 1] * nums[i + 1];
		// 处理结果数组
		vector<int> ret(n);
		for (int i = 0; i < n; i++)
			ret[i] = lprod[i] * rprod[i];
		return ret;
	}
};